package event;

import java.awt.Container;
import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Example_6_5_JComboBox extends JFrame {

	private static final long serialVersionUID = 1L;

	public Example_6_5_JComboBox() {
		super("显示组合框JComboBox");

		Container contentPane = this.getContentPane();

		/* 创建一个面板对象,指定布局管理器为GridLayout,1行2列.Jpanel的默认版面管理为FlowLayout */
		JPanel jPanel1 = new JPanel(new GridLayout(1, 2));

		//***************************方法一*************************************
		
		// 1、利用String数组建立JComboBox
		String[] fruit = { "苹果", "香蕉", "桔子", "梨", "芒果" };
		JComboBox<String> jComboBox1 = new JComboBox<String>(fruit);
		jComboBox1.addItem("其他"); // 在列表框选项的最后再添加一个"其他"选项

		// 设置jList1对象的带标题边框
		jComboBox1.setBorder(BorderFactory.createTitledBorder("您最喜欢的水果:"));
		// 添加列表框jComboBox1至面板
		jPanel1.add(jComboBox1);

		//***************************方法二*************************************
		
		// 2、利用ComboBoxModel建立JComboBox
		ComboBoxModel<String> myModel = new MyComboBoxModel();
		JComboBox<String> jComboBox2 = new JComboBox<String>(myModel);
		// 设置jList1对象的带标题边框
		jComboBox2.setBorder(BorderFactory.createTitledBorder("您最喜欢的水果:"));
		// 添加列表框jComboBox2至面板
		jPanel1.add(jComboBox2);

		// 添加面板至父容器
		contentPane.add(jPanel1);
		
		// 设置本窗体显示的初始大小
//		this.setBounds(300, 200, 350, 90);   //等价于下面两行代码
		this.setSize(350, 90);
		this.setLocation(300, 200);
		// 设置本窗体初始可见
		this.setVisible(true);
	}

	public static void main(String[] args) {
		new Example_6_5_JComboBox();

	}

}

class MyComboBoxModel extends DefaultComboBoxModel<String> {
	private static final long serialVersionUID = 1L;
	String[] fruit = { "苹果", "香蕉", "桔子", "梨", "芒果" };

	MyComboBoxModel() {
		for (int i = 0; i < fruit.length; i++) {
			/* addElement()方法用于向列表框添加选项元素 */
			this.addElement(fruit[i]);
		}
	}
}